<template>
  <el-card>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="名称" prop="rolename">
        <el-input type="text" v-model="ruleForm.rolename" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="menus">
        <el-tree
          ref="tree"
          :data="menus"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="{children: 'children',label: 'title'}"
        ></el-tree>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    const checkMenus = (rule, value, callback) => {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      if (checkedKeys.length == 0) {
        callback(new Error("请给角色分配权限"));
      } else {
        callback();
      }
    };
    return {
      menus: [],
      ruleForm: {
        rolename: "",
        status: 1
      },
      rules: {
        rolename: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        menus: [
          {
            validator: checkMenus,
            message: "请输为角色分配权限",
            trigger: "blur"
          }
        ],
        status: [{ required: true, message: "请选择角色状态", trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
        this.ruleForm.menus=this.$refs.tree.getCheckedKeys().join(',');
          const res=await this.$http.post('/api/roleadd',this.ruleForm);
          if(res.code==200){
            return  this.$success('操作成功');
          }
          this.$error('操作失败');
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 获取属性菜单
    async getMenuTree() {
      const res = await this.$http.get("/api/menulist?istree=1");
      if (res.code == 200) {
        this.menus = res.list;
      }
    }
  },
  created() {
    this.getMenuTree();
  }
};
</script>

<style>
</style>